<?php

class TesteShell extends AppShell{
	
	var $uses = array('Pagamento', 'Payment.PaymentPagamento', 'DataPagamento');
	var $curl;
	
	public function setOption($option, $value){
		curl_setopt($this->curl, $option, $value);
	}
	
	public function setData($data){
		$this->setOption(CURLOPT_POSTFIELDS, $data);
	}
	
	public function sendTransaction(){
		return (curl_exec($this->curl));
	}
	
	public function listOfCodesGeral(){
		$email = 'patriota.alexandre@gmail.com';
		$token = 'F927290493514966A3D6A9456FA9F128';
		$precos = $this->DataPagamento->find('list', array('fields'=>'preco'));
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		// 		$pagamentos = $this->PaymentPagamento->find('all');
		// 		$pagamentos = array('A8361602-A736-4CD0-B8E5-2FF78442BC01');
		// 		foreach($pagamentos as $item){
		// 			$code = $item['PaymentPagamento']['transaction_code'];
		// 			$code = $item;
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-02-01T00:00'.
		'&finalDate=2014-02-28T23:59'.
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		foreach($xml->transactions->transaction as $item){
			$status[(int)$item->status]++;
			if(in_array($item->status, array(3,4)))
			$codes[] = (string)($item->code);
		}
		pr($status);
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-03-01T00:00'.
		'&finalDate=2014-03-31T23:59'.
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		foreach($xml->transactions->transaction as $item){
			$status[(int)$item->status]++;
			if(in_array($item->status, array(3,4)))
			$codes[] = (string)($item->code);
		}
		pr($status);
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-04-01T00:00'.
		'&finalDate=2014-04-30T23:59'.
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		foreach($xml->transactions->transaction as $item){
			$status[(int)$item->status]++;
			if(in_array($item->status, array(3,4)))
			$codes[] = (string)($item->code);
		}
		pr($status);
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-05-01T00:00'.
		'&initialDate=2014-05-31T23:59'.
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		foreach($xml->transactions->transaction as $item){
			$status[(int)$item->status]++;
			if(in_array($item->status, array(3,4)))
			$codes[] = (string)($item->code);
		}
		pr($status);
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-06-01T00:00'.
		'&initialDate=2014-'.date('m').'-'.date('d').'T'.date('H').':'.date('i').
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		foreach($xml->transactions->transaction as $item){
			$status[(int)$item->status]++;
			if(in_array($item->status, array(3,4)))
				$codes[] = (string)($item->code);
		}
		sort($codes);
		foreach($codes as $item){
			$this->out($item);
		}
		pr($status);
	}
	
	public function main(){
		$email = 'patriota.alexandre@gmail.com';
		$token = 'F927290493514966A3D6A9456FA9F128';
		$pagamentos = $this->PaymentPagamento->find('all', array('conditions'=>array('transaction_code !='=>'')));
// 		$pagamentos = array(
// 			'120EC67B-4000-4A3C-9360-4C8678061078'
// 		);
		foreach($pagamentos as $item){
			$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
			$item['PaymentPagamento']['transaction_code'].
			'?email='.
			$email.
			'&token='.
			$token;
// 			$this->curl = curl_init($url);
// 			$this->setOption(CURLOPT_RETURNTRANSFER, true);
// 			$xml= simplexml_load_string(($this->sendTransaction()));
			$array[] = $item['PaymentPagamento']['transaction_code'];
// 			if(!empty($xml->grossAmount) && !empty($item['PaymentPagamento']['pagamento_system_id']) && $item['PaymentPagamento']['pagamento_system_id'] != 0){
// 				$this->PaymentPagamento->save(array('id'=>$item['PaymentPagamento']['id'],
// 						'value'=>$xml->grossAmount,
// 						'primary_paymement_method_id'=>$xml->paymentMethod->type,
// 						'secondary_paymement_method_id'=>$xml->paymentMethod->code,
// 						'status_id'=>$xml->status));
// 				echo '-------------------';
// 			}
		}
		sort($array);
		foreach($array as $item){
			$this->out($item);
		}
	}
	
	public function compare(){
		$total = file('/var/www/sinape2014/hashs do pagseguro', FILE_IGNORE_NEW_LINES);
		$abe = file('/var/www/sinape2014/ABE', FILE_IGNORE_NEW_LINES);
		$sinape = file('/var/www/sinape2014/SINAPE', FILE_IGNORE_NEW_LINES);
		$array = array();
		foreach ($total as $key=>$item){
			if(!in_array($item, $abe) && !in_array($item, $sinape)){
				$array[] = $item;
			}
		}
		foreach($array as $item){
			$this->out($item);
		}
	}
	
	public function buscaTransacao($code = null){
		$email = 'patriota.alexandre@gmail.com';
		$token = 'F927290493514966A3D6A9456FA9F128';
		$pagamentos = array($code);
		foreach($pagamentos as $item){
			$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
					$code.
					'?email='.
					$email.
					'&token='.
					$token;
			$this->curl = curl_init($url);
			$this->setOption(CURLOPT_RETURNTRANSFER, true);
			$xml= simplexml_load_string(($this->sendTransaction()));
			$this->out('Nome: '.$xml->sender->name);
			$this->out('Email: '.$xml->sender->email);
// 			pr($xml);
			// 			if(!empty($xml->grossAmount) && !empty($item['PaymentPagamento']['pagamento_system_id']) && $item['PaymentPagamento']['pagamento_system_id'] != 0){
			// 				$this->PaymentPagamento->save(array(
			// 						'id'=>$item['PaymentPagamento']['id'],
			// 						'value'=>$xml->grossAmount,
			// 						'primary_payment_method_id'=>$xml->paymentMethod->type,
			// 						'secondary_payment_method_id'=>$xml->paymentMethod->code,
			// 						'status_id'=>$xml->status,
			// 						'transaction_code' => $xml->code,
			// 						'payment_system_id'=>$xml->reference
			// 				));
			// 				echo '-------------------';
			// 			}
			// 			else{
	
			// 			}
	}
	}
	
	public function ByReference($data){
		$email = 'patriota.alexandre@gmail.com';
		$token = 'F927290493514966A3D6A9456FA9F128';
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				$data->code.
				'?email='.
				$email.
				'&token='.
				$token;
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		$db_row = $this->PaymentPagamento->findByPagamentoSystemId($data->reference);
		if($db_row){
			$this->out('---------------- Salvo -------------------');
			$to_save = array('id'=>$db_row['PaymentPagamento']['id'], 'value'=>$data->grossAmount, 'transaction_code'=>$data->code);
			$this->PaymentPagamento->save($to_save);
		}
		// 		pr($xml);
	}
	
	public function teste(){
		$email = 'patriota.alexandre@gmail.com';
		$token = 'F927290493514966A3D6A9456FA9F128';
		// 		$pagamentos = $this->PaymentPagamento->find('all');
		// 		$pagamentos = array('A8361602-A736-4CD0-B8E5-2FF78442BC01');
		// 		foreach($pagamentos as $item){
		// 			$code = $item['PaymentPagamento']['transaction_code'];
		// 			$code = $item;
		$url = 'https://ws.pagseguro.uol.com.br/v2/transactions/'.
				// 			$code.
		'?email='.
		$email.
		'&token='.
		$token.
		'&initialDate=2014-05-01T00:00'.
		'&finalDate=2014-05-22T15:01'.
		'&page=1'.
		'&maxPageResults=1000';
		$this->curl = curl_init($url);
		$this->setOption(CURLOPT_RETURNTRANSFER, true);
		$xml= simplexml_load_string(($this->sendTransaction()));
		$precos = $this->DataPagamento->find('list', array('fields'=>'preco'));
		$status = array(0=>0, 1=>0, 2=>0, 3=>0, 4=>0, 5=>0, 6=>0, 7=>0);
		foreach($xml->transactions->transaction as $item){
			$code = $item->code;
			$dados = $this->PaymentPagamento->findByTransactionCode($code);
// 			$this->out('Status: '.$item->status.' - Code: '.$code);
// 			pr($dados);
			if(!$dados && in_array($item->grossAmount, $precos) && !isset($item->reference)){
				$this->out('------------');
				$this->out('Código: '.$code);
				$this->buscaTransacao($code);
			}
			elseif(isset($item->reference) && !$dados && in_array($item->grossAmount, $precos)){
				$this->out('Código: '.$code);
				$this->out("Ref: ".$item->reference);
				$this->ByReference($item);
			}
			elseif(!$dados && in_array($item->grossAmount, $precos)){
				$this->out('Largado: '.$item->code);
			}
			if(!in_array($item->grossAmount, $precos)){
				$status[(int)$item->status]++;
			}
	
		}
		$this->out('resultsInThisPage '.$xml->resultsInThisPage);
		$this->out('currentPage '.$xml->currentPage);
		$this->out('totalPages '.$xml->totalPages);
		pr($status);
	}
	
	public function inserirpagamentozeradoporcsv(){
		$filename = "/home/willen/Documentos/usuarios.csv";
		$header = NULL;
	    $data = array();
	    if (($handle = fopen($filename, 'r')) !== FALSE)
	    {
	        while (($row = fgetcsv($handle, 1000, ';')) !== FALSE)
	        {
	            if(!$header)
	                $header = $row;
	            else
	                $data[] = array_combine($header, $row);
	        }
	        fclose($handle);
	    }
// 	    pr($data);
	    foreach($data as $item){
	    	$emails[] = $item['Email'];
	    }
	    $usuarios = $this->Pagamento->Usuario->findAllByEmail($emails);
	    $i = 0;
	    foreach($usuarios as $usuario){
	    	if(!empty($usuario['Pagamento']['id'])){
		    	$transaction = $this->PaymentPagamento->findByPagamentoSystemId($usuario['Pagamento']['id']);
		    	$this->Pagamento->id = $usuario['Pagamento']['id'];
		    	$this->Pagamento->save(array('id'=>$usuario['Pagamento']['id'], 'hash'=>'MANUAL', 'confirmado'=>1, 'valor_total'=>0.00));
		    	$this->PaymentPagamento->id = $transaction['PaymentPagamento']['id'];
		    	$this->PaymentPagamento->save(array('id'=>$transaction['PaymentPagamento']['id'], 'transaction_code'=>'MANUAL', 'status_id'=>4, 'value'=>0.00));
	    	}
	    	else{
	    		$this->Pagamento->save(array('usuario_id'=>$usuario['Usuario']['id'], 'hash'=>'MANUAL', 'confirmado'=>1, 'valor_total'=>0.00));
	    		$this->PaymentPagamento->save(array('pagamento_system_id'=>$this->Pagamento->id, 'model_pagamento'=>'Pagamento', 'transaction_code'=>'MANUAL', 'status_id'=>4, 'value'=>0.00));
	    	}
	    	unset($emails[array_search($usuario['Usuario']['email'], $emails)]);
	    }
	    pr($emails);
	    pr($i);
	}
}